<template>
    <div>
    <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <!-- 警告区域 -->
            <el-alert title="注意：只能选择三级商品" show-icon :closable="false" type="warning"></el-alert>
            <!-- 选择商品分类区域 -->
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类：</span>
                    <!-- 选择商品分类的级联选择框 -->
                    <!-- options表示数据源 -->
                    <el-cascader v-model="selectedKeys" :options="catelist" expand-trigger="hover"
                     :props="cateProps" @change="handleChange"></el-cascader>
                </el-col>
            </el-row>
                <!-- Tab栏 -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <!-- 添加动态参数面板 -->
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="mini" :disabled="isOk" @click="showDailog">添加参数</el-button>
                    <el-table :data='manyTableData' border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag closable v-for="(item,i) in scope.row.attr_vals" @close="removeTag(i,scope.row)" :key="i">{{item}}</el-tag>
                                  <!-- 文本框 -->
                                <el-input class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                    >
                                </el-input>
                                <!-- 标签 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作" >
                            <template slot-scope="scope">
                                <el-button  size="mini" type="primary" 
                                icon="el-icon-edit" @click="showeditDailog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 添加静态属性面板 -->
                <el-tab-pane label="静态属性" name="only">
                     <el-button type="primary" size="mini" :disabled="isOk"  @click="showDailog">添加属性</el-button>
                    <el-table :data='onlyTableData' border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag closable v-for="(item,i) in scope.row.attr_vals"  @close="removeTag(i,scope.row)" :key="i">{{item}}</el-tag>
                                <!-- 文本框 -->
                                <el-input class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                    >
                                </el-input>
                                <!-- 标签 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作" >
                            <template slot-scope="scope">
                                <el-button :id="scope.row" size="mini" type="primary" 
                                icon="el-icon-edit" @click="showeditDailog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
            
        </el-card>
        <!--添加 弹出框 -->
        <el-dialog :title="'添加'+titleText" :visible.sync="adddialogVisible"
            width="30%" @close="DailogClosed">
           <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
           </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="adddialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParams">确 定</el-button>
            </span>
        </el-dialog>
        <!--修改 弹出框 -->
        <el-dialog :title="'添加'+titleText" :visible.sync="editdialogVisible"
            width="30%" @close="editDailogClosed">
           <el-form :model="editForm" :rules="editFormrules" ref="editFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
           </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParams">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data(){
        return{
            //商品分类列表数据
            catelist:[],
            //级联选择框的配置对象
            cateProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            //级联选择框双向选择绑定到的数据
            selectedKeys:[],
            //被选择的Tab栏标签名称
            activeName:'many',
            //动态参数数据
            manyTableData:[],
            //静态参数数据
            onlyTableData:[],
            //弹出框的显示与隐藏
            adddialogVisible : false,
            editdialogVisible: false,
            //添加数据参数
            addForm:{
                attr_name:''
            },
            //修改数据参数
            editForm:{
                attr_name:''
            },
            //添加的验证规则
            addFormrules:{
                attr_name:[
                    { required: true, message: '请输入活动名称', trigger: 'blur' },
                ]   
            },
            //修改的验证规则
            editFormrules:{
                attr_name:[
                    { required: true, message: '请输入活动名称', trigger: 'blur' },
                ]   
            },
 
        }
    },
    created(){
        this.getCatelist();
    },
    methods:{
        //获取所有商品分类数据
        async getCatelist(){
            const {data:res} = await this.$http.get('categories');
            if(res.meta.status!=200){
                return this.$message.error('获取分类列表失败');
            }
            this.catelist = res.data;
           // console.log(this.catelist)
        },
        //级联选择框双向绑定到的
        async handleChange(){
           this.getParamsData();
        },
        //tab栏切换监听事件
        handleTabClick(){
           this.getParamsData();
        },
        //获取参数列表
        async getParamsData(){
            //如果选中的不是三级分类
            if(this.selectedKeys.length!=3){
                this.selectedKeys = [];
                this.manyTableData =[];
                this.onlyTableData = [];
            }
            //console.log(this.selectedKeys)
           
            const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{
                params:{
                     sel:this.activeName
                }
            })
            if(res.meta.status!=200){
                return this.$message.error('获取参数列表失败');
            }else{
                res.data.forEach(item=>{
                    item.attr_vals =item.attr_vals ?  item.attr_vals.split(' '):[];
                    //控制添加文本框的显示与隐藏
                    item.inputVisible = false;                  
                    //输入框的数据
                    item.inputValue='';
                })
                if(this.activeName=='many'){
                    this.manyTableData = res.data;
                }else{
                    this.onlyTableData = res.data;
                }
            }
        },
        //点击确定显示添加弹出框
        async showDailog(attr_id){
            
            this.adddialogVisible = true;
        },
        ////点击确定显示修改弹出框
        async showeditDailog(attr_id){
            const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`,
            {params:{attr_sel:this.activeName}})
                if(res.meta.status!=200) return this.$message.error('查询信息失败');
                this.editForm = res.data;
                 this.editdialogVisible = true;  
        },
        //添加对话框关闭事件
        DailogClosed(){
            this.$refs.addFormRef.resetFields();
        },
        //修改对话框关闭事件
        editDailogClosed(){
             this.$refs.editFormRef.resetFields();
        },
        //点击确定，添加数据
        addParams(){
            this.$refs.addFormRef.validate(async valid=>{
                if(!valid) return this.$message.info('请输入名称');
                const {data:res} = await this.$http.post(`categories/${this.cateId}/attributes`,{
                    attr_name:this.addForm.attr_name,
                    attr_sel:this.activeName
                })
                if(res.meta.status!=201) return this.$message.error('添加失败');
                this.$message.success('添加成功');
                this.getParamsData();
                this.adddialogVisible = false;
            })
        },
        //点击确定，修改数据
        editParams(){
            this.$refs.editFormRef.validate(async valid=>{
                if(!valid) return this.$message.info('请输入名称');
                const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{
                    attr_name:this.editForm.attr_name,
                    attr_sel:this.activeName
                })
                if(res.meta.status!=200) return this.$message.error('修改失败');
                this.$message.success('修改成功');
                this.getParamsData();
                this.editdialogVisible = false;
            })
        },
        //删除参数
        async removeParams(attr_id){
             const result = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                 type: 'warning'
            }).catch(err=>err)
            if(result=='cancel')  return this.$message.info('取消删除');
            const {data:res} = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
                if(res.meta.status!=200) return this.$message.error('删除失败');
                this.$message.success('删除成功');
                this.getParamsData();
        },
        //控制回车或失去焦点触发事件
        async handleInputConfirm(row){
            //如果没有输入内容
            if(row.inputValue.trim().length==0){
                row.inputValue='';
                row.inputVisible = false;
                return;
            }
          // console.log('ok'); 
          row.attr_vals.push(row.inputValue.trim());
          row.inputValue='';
           row.inputVisible = false;
           this.saveAttrs(row); 
        },
        //向服务器端发送请求，保存数据
        async saveAttrs(row){
            const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                    attr_name:row.attr_name,
                    attr_sel:this.activeName,
                    attr_vals:row.attr_vals.join(' ')
                })
                if(res.meta.status!=200) return this.$message.error('添加参数失败');
                this.$message.success('添加参数成功');
        },
        //控制添加标签文本框显示
        showInput(row){
            row.inputVisible = true;
            //文本框自动获得焦点
            //$nextTick的用法，当页面中的元素重新渲染后，才会调用回调函数
             this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        //删除标签
        removeTag(i,row){
            row.attr_vals.splice(i,1);
            this.saveAttrs(row);
        }
    },
    computed:{
        isOk(){
            if(this.selectedKeys.length!=3){
                return true
            }else{
                return false
            }
        },
        cateId(){
            if(this.selectedKeys.length==3){
                return this.selectedKeys[2]
            }else{
                return null
            }
        },
        titleText(){
            if(this.activeName=='many'){
                return '参数名称'
            }else{
                return '属性名称' 
            }
        }
    }
}
</script>

<style lang="less" scoped>
.cat_opt{
    margin:15px 0;
}
.el-tag{
    margin:0 15px;
}
.input-new-tag{
    width: 100px;
}
</style>